package com.example.module_motocircle.ui.post.detail

import android.util.Log
import androidx.lifecycle.viewModelScope
import com.example.lib_common.base.BaseViewModel
import com.example.lib_common.base.state.Empty
import com.example.lib_common.base.state.Failed
import com.example.lib_common.base.state.Loading
import com.example.lib_common.base.state.RequestEvent
import com.example.lib_common.base.state.Success
import com.example.module_motocircle.model.CommentsModel
import com.example.module_motocircle.model.PostCommentsModel
import com.example.module_motocircle.model.PostModel
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.asSharedFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.zip
import kotlinx.coroutines.launch
import javax.inject.Inject

/**
 * @author yaotianxue
 * @description
 * @date 2025/6/3
 */
@HiltViewModel
class PostDetailViewModel @Inject constructor(private val repository: PostDetailRepository): BaseViewModel() {

    private var currentPage = 1
    private var defaultPageSize = 10
    //记录第一页当前展开的一级评论
    val needExpendComment = mutableListOf<String>()
    val showAllCommentsFlow = MutableSharedFlow<List<Int>>()
    val mLoadCommentsPageEvent = MutableSharedFlow<LoadPageEvent>()
    private var totalPage = 1
    var commentSize=0

    //var currentPost:PostItem? = null
    var currentPost:PostModel? = null
    var afterSale:List<AfterSalePageItem>? = null
    var currentCommentsList: MutableList<PostCommentsModel> = mutableListOf()
    var formatCommentsList: MutableList<PostCommentsModel> = mutableListOf()

    private val mPostState_:MutableStateFlow<RequestEvent> = MutableStateFlow(Loading)
    val mPostState = mPostState_.asStateFlow()


    fun getPostDetailData(pageNum: Int, pageSize: Int = 10){
        execute(
            action = repository.getPostDetail(),
            onError = {

            },
            onFinish = {
                currentPost = it.data
                if(it != null){
                    repository.getAfterSale() //售后信息
                        .zip(repository.queryPostCommentsByPage(pageNum,pageSize)) { afterSale, comments -> //评论信息
                            this.afterSale = afterSale.data

                            totalPage = comments.data!!.pages
                            //currentPage = comments.data!!.current
                            //保存评论信息
                            this.currentCommentsList = comments.data.comments
                            this.commentSize = comments.data.total
                            formatCommentsList.clear()
                            //处理获取到的评论数据
                            formatComments(currentCommentsList)

                            currentPost //帖子信息
                        }.collect{ //帖子信息
                            if (it != null){
                                mPostState_.value = Success
                            }

                        }
                }


            }

        )
    }

    fun loadCommentsByPage() {
        val loadPage = currentPage + 1
        if (loadPage > totalPage) {
            viewModelScope.launch {
                mLoadCommentsPageEvent.emit(NoMore)
            }
            return
        }

        execute(
            action = repository.queryPostCommentsByPage(loadPage, defaultPageSize),
            onStart = {
                mLoadCommentsPageEvent.emit(com.example.module_motocircle.ui.post.detail.Loading)
            },
            onFinish = {
                if (it.data != null) {
                    currentPage = it.data!!.current
                    totalPage = it.data!!.pages
                    val start = formatCommentsList.size
                    val count = it.data!!.comments.size
                    currentCommentsList.addAll(it.data!!.comments)
                    formatComments(it.data!!.comments)
                    mLoadCommentsPageEvent.emit(Success(start, count))
                } else {
                    mLoadCommentsPageEvent.emit(LoadFailed("数据为空"))
                }
            },
            onError = {
                mLoadCommentsPageEvent.emit(LoadFailed(it))
            }
        )
    }
    //获取第一页评论数(包含子级)
    fun get1stPageCommentsNum(): Int {
        var size = 0
        currentCommentsList.filterIndexed { index, _ -> index < defaultPageSize }.forEach {
            size++
            size += it.twoLevel?.size ?: 0
        }
        return size
    }

    //处理子评论展开
    fun handleShowAllComments(postCommentsModel: CommentsModel, position: Int) {
        viewModelScope.launch {
            needExpendComment.add(postCommentsModel.parentId)
            val comment =
                currentCommentsList.firstOrNull { it.postsCommentId == postCommentsModel.parentId }
                    ?: return@launch

            val allChild = comment.twoLevel ?: return@launch
            //view标志处理
            allChild.forEachIndexed { index, c ->
                if (index == 0) {
                    c.topRound = true
                    c.bottomRound = false
                    c.rect = false
                } else if (index > 0 && index < allChild.size - 1) {
                    c.topRound = false
                    c.bottomRound = false
                    c.rect = true
                } else {
                    c.topRound = false
                    c.rect = false
                    c.bottomRound = true
                }
                c.twoLevelSize = 0
            }
            val new = mutableListOf<PostCommentsModel>()
            val before = formatCommentsList.subList(0, position)
            val after = formatCommentsList.subList(position + 1, formatCommentsList.size)
            new.addAll(before)
            new.addAll(allChild)
            new.addAll(after)
            formatCommentsList = new
            val end = position + allChild.size - 1
            showAllCommentsFlow.emit(listOf(position, end))
        }
    }

    private fun formatComments(it: List<PostCommentsModel>) {
        it.forEach {
            formatCommentsList.add(it)
            it.isFirstLevel = true
            if (it.twoLevel?.isNotEmpty() == true) {
                if (needExpendComment.any { commentId -> commentId == it.postsCommentId }) {
                    //需要展开
                    it.twoLevel.forEachIndexed { index, replyComments ->
                        replyComments.isFirstLevel = false
                        if (index == 0) {
                            replyComments.topRound = true
                        } else if (index > 0 && index < it.twoLevel.size - 1) {
                            replyComments.rect = true
                        } else {
                            replyComments.bottomRound = true
                        }
                        replyComments.twoLevelSize = 0
                    }
                    formatCommentsList.addAll(it.twoLevel)
                } else {
                    //折叠情况
                    val replyComments = it.twoLevel[0]
                    replyComments.twoLevelSize = it.twoLevel.size
                    replyComments.isFirstLevel = false
                    formatCommentsList.add(replyComments)
                }

            }
        }
    }




//    /*
//    获得帖子详情
//     */
//    private val mPostDetail_ = MutableSharedFlow<RequestEvent>()
//    val mPostDetail = mPostDetail_.asSharedFlow()
//    var mSearchKeyWordLiveData =PostDetailEntity
//
//        fun postDetail() {
//        execute(
//            action = repository.postDetail(),
//            onStart = {
//                mPostDetail_.emit(Loading)
//            },
//            onError = {
//                mPostDetail_.emit(Failed(it))
//            },
//            onFinish = {
//               if (it.data){
//                   mPostDetail_.emit(Empty)
//               }else{
//                   mSearchKeyWordLiveData  = it.data
//                   mPostDetail_.emit(Success)
//               }
//            }
//        )


}
//分页加载数据状态
sealed class LoadPageEvent

object None : LoadPageEvent()
object Loading : LoadPageEvent()
class Success(val start: Int, val count: Int) : LoadPageEvent()
object NoMore : LoadPageEvent()
class LoadFailed(val msg: String) : LoadPageEvent()